package com.xlh.virtualization.job.delayed;

import cn.hutool.core.date.DateUtil;
import com.xlh.util.SpringContextUtil;
import com.xlh.virtualization.domain.ContainerContext;
import com.xlh.virtualization.service.ContainerService;
import com.xlh.virtualization.service.ExperimentService;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import static com.xlh.virtualization.constant.ContainerConstant.CONTAINER_STOP_DELAYED_TIME;

/**
 * @author cheer
 */
public class StopContainerTask implements Delayed, Runnable {

    private static ExperimentService experimentService = SpringContextUtil.getBean(ExperimentService.class);

    private static ContainerService containerService = SpringContextUtil.getBean(ContainerService.class);

    private ContainerContext containerContext;

    /**
     * 过期时间，单位：秒
     */
    private Long expireTime;

    public StopContainerTask(ContainerContext containerContext) {
        this.containerContext = containerContext;
        this.expireTime = DateUtil.currentSeconds() + (long) CONTAINER_STOP_DELAYED_TIME;
    }

    public StopContainerTask(Long userId, Integer contextType, Long contextId) {
        this.containerContext = new ContainerContext()
                .setUserId(userId)
                .setContextType(contextType)
                .setContextId(contextId);
        this.expireTime = DateUtil.currentSeconds() + (long) CONTAINER_STOP_DELAYED_TIME;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expireTime - DateUtil.currentSeconds(), TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        if (!experimentService.isExperimentPageOpen(containerContext.getUserId(), containerContext.getContextType(), containerContext.getContextId())) {
            containerService.stopContainerByContext(containerContext);
        }
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof StopContainerTask) {
            StopContainerTask other = (StopContainerTask) o;
            if (expireTime < other.expireTime) {
                return -1;
            } else if (expireTime > other.expireTime) {
                return 1;
            }
        }
        return 0;
    }

    public ContainerContext getContainerContext() {
        return containerContext;
    }

    public Long getUserId() {
        return containerContext.getUserId();
    }

    public Integer getContextType() {
        return containerContext.getContextType();
    }

    public Long getContextId() {
        return containerContext.getContextId();
    }
}
